<?php

/**
 * @see http://www.zendcasts.com/writing-composite-zend_form-elements/2010/03/ 
 */
class ZFKiller_Form_Element_Dddtelefone extends ZFKiller_Form_Element_Text {

	public $helper = 'formDddtelefone';
	protected $_value = array('ddd' => '', 'number' => '');

	public function __construct($spec, $options = null) {
		if (!isset($options['description'])) {
			$options['description'] = 'Informe o DDD e o telefone.';
		}
        
		parent::__construct($spec, $options);
	}

	public function isValid($value, $context = null) {
		$this->setValue($value);
		$value = $this->getValue();

		$temVazio = ($value['ddd'] == '') or ($value['number']);

		if ((!$this->isRequired()) && $temVazio) {
			return true;
		}

		$this->_messages = array();
		$this->_errors = array();
		$result = true;

		$dddtelefoneValidator = new ZFKiller_Validate_Dddtelefone();
		if (!$dddtelefoneValidator->isValid($value)) {
			$result = false;
			$messages = $dddtelefoneValidator->getMessages();
			$errors = array_keys($messages);

			$this->_messages = array_merge($this->_messages, $messages);
			$this->_errors = array_merge($this->_errors, $errors);
		}
		
		return $result;
	}

	public function setValue($value) {
		if ((is_array($value)) and (isset($value['ddd'])) and (isset($value['number']))) {
			$digitsFilter = new Zend_Filter_Digits();
			$value['ddd'] = $digitsFilter->filter($value['ddd']);
			$value['number'] = $digitsFilter->filter($value['number']);

			parent::setValue($value);
		}

		return $this;
	}

}